package com.flx.noodle.websocket.controller;

import com.flx.noodle.websocket.entity.SSOUser;
import com.flx.noodle.websocket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import util.WsConstant;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * Created by fenglixiong on 2017/10/2.
 */
@Controller
@RequestMapping("/home")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login.htm")
    public String login(@RequestParam(value = "username")String userName,
                        @RequestParam(value = "password")String password,
                        ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {

        SSOUser ssoUser = userService.getUserByName(userName);
        if(ssoUser==null){
            model.addAttribute("message","用户不存在！");
            System.out.println("用户不存在！");
            return "home/index";
        }
        if(!ssoUser.getPassWord().equals(password)){
            model.addAttribute("message","密码错误！");
            System.out.println("密码错误！");
            return "home/index";
        }else {
            System.out.println("登录成功！");
            //HttpServletRequest.getSession().getId()是服务器端的概念
            //HttpServletRequest.getRequestedSessionId()是客户端就是浏览器的概念。
            String sessionId = request.getSession().getId();
            System.out.println("SessionId="+sessionId);
            //登陆成功存储sessionId
            ssoUser.setSessionId(sessionId);
            ssoUser.setSessionCreateTime(new Date());
            request.getSession().setAttribute(WsConstant.WEBSOCKET_SESSION_KEY,ssoUser);
            //每次登陆重新更新用户的sessionId记录到数据库
            int ret = userService.updateSessionId(ssoUser.getUserId(),sessionId);
            if(ret>0){
                System.out.println("更新用户sessionId到数据库成功！");
            }
            //设置Cookie
            String cookieValue = URLEncoder.encode(sessionId+"@"+"tom@jerry","UTF-8");
            Cookie cookie = new Cookie(WsConstant.SESSION_COOKIE_KEY,cookieValue);
            cookie.setPath("/");
            Cookie lastVisitTime = new Cookie(WsConstant.USER_LAST_VISIT_TIME,System.currentTimeMillis()+"");
            lastVisitTime.setPath("/");
            response.addCookie(cookie);
            response.addCookie(lastVisitTime);
        }
        response.sendRedirect("/user/userList.htm");
        return null;
    }

}
